package com.hx.util.mail;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class JavaMail {
	private String host;
	private String from;
	private String to;
	private String subject;
	private String content;
	private boolean authentication;
	private String username;
	private String password;

	public void sendMail(String host, String from, String to, String subject,
			String content, boolean authentication, String username,
			String password) throws MessagingException {

		Properties props = System.getProperties();

		if(this.host.indexOf("smtp.gmail.com")>=0)//注意此处 加了判断 因为gmail的端口是465
        {
			props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 
			props.setProperty("mail.smtp.socketFactory.fallback", "false"); 
			props.setProperty("mail.smtp.port", "465"); 
			props.setProperty("mail.smtp.socketFactory.port", "465"); 
        }else{
    		props.put("mail.smtp.host", host);
    		if (!authentication) {
    			props.put("mail.smtp.auth", "false");
    		} else {
    			props.put("mail.smtp.auth", "true");
    		}
        	
        }

		Session session = Session.getDefaultInstance(props, null);

		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(from));
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
		message.setSubject(subject);
		message.setContent(content, "text/html;charset=gb2312");

		if (authentication) {
			Transport smtp = null;
			try {
				smtp = session.getTransport("smtp");
				smtp.connect(host, username, password);
				smtp.sendMessage(message, message.getAllRecipients());
			} catch (AddressException e) {
				e.printStackTrace();
			} catch (MessagingException e) {
				e.printStackTrace();
			} finally {
				smtp.close();
			}
		} else {
			Transport.send(message);
		}
	}

	public void send() throws MessagingException {
		host = "smtp.daodaoly.com";//smtp服务器
		from = "duanshihao@daodaoly.com";
		to = "549290859@qq.com";  //发送给谁
		subject = "just for test";  //标题
		content = "Beijing Olympic"; //内容
		authentication = true;
		username = "duanshihao";  // 登陆邮件发送服务器的用户名 
		password = "daodaor.com1988"; // 登陆邮件发送服务器的密码 
		sendMail(host, from, to, subject, content, authentication, username,
				password);
	}

	public static void main(String args[]) throws MessagingException {
		JavaMail jm = new JavaMail();
		jm.send();
	}
}
